package com.example.runningman.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.runningman.R;
import com.example.runningman.adapter.Art_adapter;
import com.example.runningman.bean.Art;
import com.example.runningman.bean.User;
import com.example.runningman.friend.SelfActivity;
import com.example.runningman.friend.WritActivity;
import com.example.runningman.run.DynamicDemo;
import com.example.runningman.user.LoginActivity;

import com.example.runningman.user.RegisterActivity;
import com.example.runningman.util.GlideBlurTransformation;
import com.example.runningman.util.SPUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * A simple {@link Fragment} subclass.
 */
public class FindFragment extends BaseFragment {
    ImageView blurImageView;
    ImageView avatarImageView;
    RecyclerView mRecyclerView;
    private ImageView reg;
    Button writ_btn;
    LinearLayoutManager layoutManager;
    static Art_adapter art_adapter;
    static List<Art> list=new ArrayList<>();
    static Gson gson=new Gson();
    SwipeRefreshLayout swipeRefreshLayout;
    public FindFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_find, container, false);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mHandler = new Mhandler();
        mRecyclerView = getActivity().findViewById(R.id.artica_recy);
        art_adapter = new Art_adapter(list, getActivity());
        layoutManager = new LinearLayoutManager(getActivity());
        swipeRefreshLayout=getActivity().findViewById(R.id.swip);
        swipeRefreshLayout.setColorSchemeResources(R.color.blue);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(art_adapter);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //这里获取数据的逻辑
                postRequest();
                art_adapter.refresh(list);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        blurImageView=getActivity().findViewById(R.id.pic_bg);
        avatarImageView = getActivity().findViewById(R.id.picd);
        String photo= SPUtil.getInstance(getActivity()).getString("photo");
        writ_btn=getActivity().findViewById(R.id.writ);
        Glide.with(getActivity()).load(photo)
                .apply(RequestOptions.bitmapTransform(new GlideBlurTransformation(getActivity())))
                .into(blurImageView);
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.h_head)
                .override(80, 80)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(getActivity()).load(photo).apply(options).into(avatarImageView);

        avatarImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                intent = new Intent(getActivity(), SelfActivity.class);
                startActivity(intent);
            }
        });
        writ_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                intent = new Intent(getActivity(), WritActivity.class);
                startActivity(intent);
            }
        });
        postRequest();
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.CART_BROADCAST");
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent){
                String msg = intent.getStringExtra("data");
                if("refresh".equals(msg)){
                    postRequest();
                }
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
//        dyn=getActivity().findViewById(R.id.dyn);
//        dyn.setOnClickListener(this::onClick);
    }
//    @Override
//    public void onClick(View v) {
//        Intent intent;
//        switch (v.getId()) {
//            case R.id.dyn:
//
//                intent = new Intent(getActivity(), DynamicDemo.class);
//                startActivity(intent);
//                break;
//            case R.id.h_head:
//                intent = new Intent(getActivity(), LoginActivity.class);
//                startActivity(intent);
//                break;
//            default:
//                break;
//        }
//    }



    public Mhandler mHandler;

    final OkHttpClient client = new OkHttpClient();
    private static class Mhandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);
                 list=gson.fromJson(ReturnMessage, new TypeToken<List<Art>>(){}.getType());
                art_adapter.refresh(list);
                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
        }
    }










    /**
     * post请求后台
     */
    private void postRequest()  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/getArt?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
